package com.hq.fxh.Vidoe;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore.MediaColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

 import com.hq.fxh.R;
import com.hq.fxh.Vidoe.tools.GetSignTask;
import com.tencent.upload.Const.FileType;
import com.tencent.upload.UploadManager;
import com.tencent.upload.task.Dentry;
import com.tencent.upload.task.ITask.TaskState;
import com.tencent.upload.task.data.FileInfo;
import com.tencent.upload.task.impl.ObjectDeleteTask;
import com.tencent.upload.task.impl.ObjectStatTask;
import com.tencent.upload.task.impl.VideoUploadTask;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class QcloudVideoActivity extends Activity implements OnClickListener {

    private static int RESULT_LOAD_IMAGE = 1;
    private static int RESULT_LOAD_VIDEO = 2;


    private FileType mFileType;
    private String videoSaveName;
    private String mFilePath = null;
    private ImageView mImageView;
    private UploadManager mFileUploadManager = null;

    private String signUrl = null;
    private String oneSign = "http://203.195.194.28/php/getsignv2.php?bucket=baronjia&service=cos&expired=0&path=";

    private String result = null;
    private String appid = null;
    private String bucket = null;
    private String sign = null;
    private String signOne = null;
    private String persistenceId = null;
    private ProgressDialog m_pDialog = null;

    private TextView mTextOutput;
    private TextView mTextUrl;
    private TextView mTextDetail;
    private VideoUploadTask videoUploadTask = null;
    private FileInfo mCurrPhotoInfo = null;

    private Handler mMainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qcloud_video);
        // UI
        setUI();

        appid = "299201";
        bucket = "vincentsu";


        GetSignTask task = new GetSignTask(this, appid, FileType.Video, bucket,
                null, null, new GetSignTask.OnGetSignListener() {

            @Override
            public void onSign(String result) {
                // TODO Auto-generated method stub
                sign = result;
            }
        });
        task.execute();

        persistenceId = "videPersistenceId";
        mFileUploadManager = new UploadManager(this, appid, FileType.Video,
                persistenceId);
    }


    public void upLoadVideo(boolean to_over_write) {
        UpLoadVideoUtils.upLoadCoverImg(this, "biaoti", null);
        //if(mFilePath == null) mFilePath="/storage/emulated/0/DCIM/Camera/VID_20160628_165340.mp4";
     /*   if (mFilePath == null) {
            Toast.makeText(this, "��ѡ���ļ�", Toast.LENGTH_SHORT).show();
            return;
        }
        VideoAttr videoAttr = new VideoAttr();
        videoAttr.isCheck = false;
        videoAttr.title = "red-1";
        videoAttr.desc = "cos-video-desc" + mFilePath;

        String[] strarray = mFilePath.split("[/]");
        videoSaveName = strarray[strarray.length - 1];

        m_pDialog.show();


        videoUploadTask = new VideoUploadTask(bucket, mFilePath, "/"
                + videoSaveName, "", videoAttr, to_over_write, new IUploadTaskListener() {
            @Override
            public void onUploadSucceed(final FileInfo result) {
                mMainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        mCurrPhotoInfo = result;
                        mTextOutput.setText("sd");
                        mTextUrl.setText(Html.fromHtml("<u>" + result.url
                                + "</u>"));
                        mTextDetail.setText("");
                        m_pDialog.hide();
                    }
                });
            }

            @Override
            public void onUploadStateChange(TaskState state) {

            }

            @Override
            public void onUploadProgress(final long totalSize,
                                         final long sendSize) {
                long p = (long) ((sendSize * 100) / (totalSize * 1.0f));
                Log.i("jia", "sd: " + p + "%");
                mMainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        long p = (long) ((sendSize * 100) / (totalSize * 1.0f));
                        m_pDialog.setMessage("sdff: " + p + "%");
                    }
                });
            }

            @Override
            public void onUploadFailed(final int errorCode,
                                       final String errorMsg) {
                Log.i("jia", "ret" + errorCode + " msg:" + errorMsg);

                mMainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        m_pDialog.hide();
                        Toast.makeText(getApplicationContext(),
                                errorCode + " msg:" + errorMsg,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        videoUploadTask.authIsEmpty();

        videoUploadTask.setAuth(sign);
        mFileUploadManager.upload(videoUploadTask); // ��ʼ�ϴ�*/
    }


    public void queryImg() {
        ObjectStatTask filetask = null;
        filetask = new ObjectStatTask(FileType.Video, bucket, "/"
                + videoSaveName, Dentry.VIDEO, new ObjectStatTask.IListener() {
            @Override
            public void onSuccess(final ObjectStatTask.CmdTaskRsp result) {

                mMainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Log.i("jia", "-------:query:");
                        Dentry dentry = result.inode;
                        String info = "name:" + dentry.name + "\n";
                        info += " sha:" + dentry.sha + "\n";
                        info += " path:" + dentry.path + "\n";
                        info += " type:" + dentry.type + "\n";
                        info += " accessUrl:" + dentry.accessUrl + "\n";
                        info += " attribute:" + dentry.attribute + "\n";
                        info += " fileSize:" + dentry.fileSize + "\n";
                        info += " fileLength:" + dentry.fileLength + "\n";
                        info += " createTime:" + dentry.createTime + "\n";
                        info += " modifyTime:" + dentry.modifyTime + "\n";
                        info += " authority:" + dentry.eauth;
                        Log.i("jia", "-------:query:" + info);
                        mTextUrl.setText(info);
                    }
                });
            }

            @Override
            public void onFailure(final int ret, final String msg) {
                Log.d("jia", "ret:" + ret + " msg:" + msg);
                mMainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        mTextUrl.setText("ret" + ret + ":msg =" + msg);
                    }
                });
            }
        });
        filetask.setAuth(sign);
        mFileUploadManager.sendCommand(filetask);
    }


    public void deleteImg() {
        Log.w("test", "name=" + videoSaveName);
        GetSignTask task = new GetSignTask(this, appid, FileType.Video, bucket,
                "/" + videoSaveName, null,
                new GetSignTask.OnGetSignListener() {

                    @Override
                    public void onSign(String sign) {
                        // TODO Auto-generated method stub

                        ObjectDeleteTask filetask = null;
                        filetask = new ObjectDeleteTask(FileType.Video, bucket,
                                "/" + videoSaveName, Dentry.VIDEO,
                                new ObjectDeleteTask.IListener() {

                                    @Override
                                    public void onSuccess(
                                            ObjectDeleteTask.CmdTaskRsp result) {
                                        mMainHandler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                mTextOutput.setText("ds");
                                                mTextDetail.setText("");
                                            }
                                        });
                                    }

                                    @Override
                                    public void onFailure(final int ret,
                                                          final String msg) {
                                        mMainHandler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                mTextOutput.setText("ret"
                                                        + ret
                                                        + " msg:"
                                                        + msg);
                                            }
                                        });
                                    }
                                });

                        filetask.setAuth(sign);
                        mFileUploadManager.sendCommand(filetask);
                    }
                });

        task.execute();

    }

    public void pause() {

        if (videoUploadTask == null
                || videoUploadTask.getTaskState() == TaskState.SUCCEED) {
            Toast.makeText(this, "ds", Toast.LENGTH_SHORT).show();
            return;
        }
        mFileUploadManager.pause(videoUploadTask.getTaskId());
    }


    private void getUploadImageSign(final String s) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub

                Log.w("test", "update sign cgi:" + s);
                try {
                    URL url = new URL(s);
                    HttpURLConnection urlConnection = (HttpURLConnection) url
                            .openConnection();
                    InputStreamReader in = new InputStreamReader(urlConnection
                            .getInputStream());
                    BufferedReader buffer = new BufferedReader(in);
                    String inputLine = null;

                    result = "";
                    while ((inputLine = buffer.readLine()) != null) {
                        result += inputLine;
                    }

                    if (result == null) Log.w("test", "result==null");
                    JSONObject jsonData = new JSONObject(result);
                    String data = jsonData.getString("data");
                    JSONObject jsonSign = new JSONObject(data);
                    sign = jsonSign.getString("sign");

                    if (sign == null)
                        Toast.makeText(QcloudVideoActivity.this, "sd", Toast.LENGTH_SHORT).show();
                    else Toast.makeText(QcloudVideoActivity.this, "sdf", Toast.LENGTH_SHORT).show();

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.w("test", "fds");
                } finally {
                    //m_pDialog.hide();
                }
            }
        }).start();
    }


    public void setUI() {
        Button btnChoosePic = (Button) findViewById(R.id.chooseFile);
        Button btnUpload = (Button) findViewById(R.id.upload);
        Button btnPause = (Button) findViewById(R.id.pause);
        Button btnDelete = (Button) findViewById(R.id.delete);
        Button btnQuery = (Button) findViewById(R.id.query);
        Button btnCover = (Button) findViewById(R.id.cover);

        btnChoosePic.setOnClickListener(this);
        btnUpload.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
        btnQuery.setOnClickListener(this);
        btnCover.setOnClickListener(this);

        mImageView = (ImageView) findViewById(R.id.imgView);
        mTextOutput = (TextView) findViewById(R.id.output);
        mTextUrl = (TextView) findViewById(R.id.url);
        mTextUrl.setOnClickListener(this);
        mTextDetail = (TextView) findViewById(R.id.detail);
        mTextUrl.setText("");
        mTextDetail.setText("");

        m_pDialog = new ProgressDialog(QcloudVideoActivity.this);
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        m_pDialog.setIndeterminate(false);
        m_pDialog.setCancelable(false);
    }

    public void chooseFile(FileType type) {
        Uri uri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        int resultCode = RESULT_LOAD_VIDEO;
        if (type == FileType.Video) {
            uri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            resultCode = RESULT_LOAD_VIDEO;
        }
        Intent i = new Intent(Intent.ACTION_PICK, uri);
        startActivityForResult(i, resultCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK || data == null)
            return;

        try {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaColumns.DATA};
            Cursor cursor = this.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                mFilePath = cursor.getString(column_index);
            }
            cursor.close();
            mImageView.setImageResource(R.mipmap.ic_launcher);
        } catch (Exception e) {
            Log.e("Demo", "choose file error!", e);
        }
    }

    public void toViewFile() {
        Log.d("jia", "toViewFile");

        Intent intent = new Intent();

        Log.d("jia", "-----:" + mTextUrl.getText().toString());
     /*   intent.putExtra("img", mTextUrl.getText().toString());
        intent.setClass(QcloudVideoActivity.this, VideoDownLoadActivity.class);
        startActivity(intent);*/
    }

    public void onUploadClicked(boolean onlyinsert) {
        Log.d("jia", "onUploadClicked");
        if (TextUtils.isEmpty(mFilePath)) {
            Toast.makeText(this, "dsf", Toast.LENGTH_SHORT).show();
            return;
        }
        upLoadVideo(onlyinsert);
    }

    public void onPauseClicked() {
        pause();
    }

    public void onDeleteClicked() {
        if (mCurrPhotoInfo == null) {
            Toast.makeText(getApplicationContext(), "dsf",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        deleteImg();
    }

    public void onQueryFileClicked() {
        Log.d("jia", "onQueryFileClicked");
        if (mCurrPhotoInfo == null) {
            Toast.makeText(this, "ds.", Toast.LENGTH_SHORT).show();
            return;
        }
        queryImg();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {
            case R.id.chooseFile:
                chooseFile(mFileType);
                break;
            case R.id.cover:
                onUploadClicked(false);
                //upLoadVideo(false);
                break;
            case R.id.upload:
                //onUploadClicked(true);
                upLoadVideo(true);
                break;
            case R.id.url:
                toViewFile();
                break;
            case R.id.pause:
                onPauseClicked();
                pause();
                break;
            case R.id.delete:
                onDeleteClicked();
                break;
            case R.id.query:
                onQueryFileClicked();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
         return true;
    }

}
